{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "afd01309",
   "metadata": {},
   "source": [
    "## Self Supervised Pretraining for Tabular Data\n",
    "\n",
    "We have implemented two Self Supervised Pre-training routines that allow the user to pre-train *all* tabular models in the library with the exception of the TabPerceiver (which is a special monster).\n",
    "\n",
    "The two routines implemented are illustrated in the figures below. The 1st is from [TabNet: Attentive Interpretable Tabular Learning](https://arxiv.org/abs/1908.07442) and is designed for models that do not use transformer-based architectures, while the second is from [SAINT: Improved Neural Networks for Tabular Data via Row Attention and Contrastive Pre-Training](https://arxiv.org/abs/2106.01342), and is designed for models that use transformer-based architectures.\n",
    "\n",
    "<p align=\"center\">\n",
    "  <img width=\"800\" src=\"figures/self_supervised_tabnet.png\">\n",
    "</p>\n",
    "\n",
    "Fig 1. Figure 2 in their paper. I have included de original caption in case is useful, althought the Figure itself is pretty self explanatory\n",
    "\n",
    "\n",
    "<p align=\"center\">\n",
    "  <img width=\"600\" src=\"figures/self_supervised_saint.png\">\n",
    "</p>\n",
    "\n",
    "Fig 2. Figure 1 in their paper. Here the caption is necessary 😏\n",
    "\n",
    "\n",
    "It is beyond the scope of this notebook to explain in detail those implementations. Therefore, we strongly recommend the user to go and read the papers if this functionality is of interest to her/him.\n",
    "\n",
    "One thing is worth noticing however. As seen in Fig 1(the TabNet paper's Fig 2) the masking of the input features happens in the feature space. However, the implementation in this library is inspired by that at the [dreamquark-ai](https://github.com/dreamquark-ai/tabnet) repo, which is in itself inspired by the original implementation (by the way, at this point I will write it once again. All TabNet related things in this library are inspired when not directly based in the code in that repo, therefore, ALL CREDIT TO THE GUYS AT dreamquark-ai).\n",
    "\n",
    "In that implementation the masking happens in the embedding space, and currently does not mask the entire embedding (i.e. categorical feature). We decided to release as it is in this version and we will implement the exact same process described in the paper in future releases. \n",
    "\n",
    "Having said all of the above let's see how to use self supervision for tabular data with `pytorch-widedeep`. We will concentrate in this notebook on the 2nd of the two approaches (the 'SAINT approach'). For details on the 1st approach (the 'TabNet' approach) please see `16_Self_Supervised_Pretraning_pt1`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8353de0",
   "metadata": {},
   "source": [
    "### Self Supervision transformer-based models..\n",
    "\n",
    "...or in general, for models where the embeddigns have all the same dimensions. In this library, these are:\n",
    "\n",
    "- TabTransformer\n",
    "- FTTransformer\n",
    "- SAINT\n",
    "- TabFastFormer\n",
    "\n",
    "Note that there is one additional Transformer-based model, the `TabPerceiver`, however this is a \"particular\" model and at the moment we do not support self supervision for it, but it will come. \n",
    "\n",
    "Let see at one example using the `FTTransformer`. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "e5b94ab2",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/javierrodriguezzaurin/.pyenv/versions/3.10.15/envs/widedeep310/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "from sklearn.metrics import accuracy_score\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "from pytorch_widedeep import Trainer\n",
    "from pytorch_widedeep.models import WideDeep, FTTransformer\n",
    "from pytorch_widedeep.metrics import Accuracy\n",
    "from pytorch_widedeep.datasets import load_adult\n",
    "from pytorch_widedeep.preprocessing import TabPreprocessor\n",
    "from pytorch_widedeep.self_supervised_training import (\n",
    "    ContrastiveDenoisingTrainer,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "1eae9832",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/javierrodriguezzaurin/Projects/pytorch-widedeep/pytorch_widedeep/preprocessing/tab_preprocessor.py:364: UserWarning: Continuous columns will not be normalised\n",
      "  warnings.warn(\"Continuous columns will not be normalised\")\n"
     ]
    }
   ],
   "source": [
    "df = load_adult(as_frame=True)\n",
    "df.columns = [c.replace(\"-\", \"_\") for c in df.columns]\n",
    "df[\"income_label\"] = (df[\"income\"].apply(lambda x: \">50K\" in x)).astype(int)\n",
    "df.drop(\"income\", axis=1, inplace=True)\n",
    "\n",
    "# one could chose to use a validation set for early stopping, hyperparam\n",
    "# optimization, etc. This is just an example, so we simply use train/test\n",
    "# split\n",
    "df_tr, df_te = train_test_split(df, test_size=0.2, stratify=df.income_label)\n",
    "\n",
    "cat_embed_cols = [\n",
    "    \"workclass\",\n",
    "    \"education\",\n",
    "    \"marital_status\",\n",
    "    \"occupation\",\n",
    "    \"relationship\",\n",
    "    \"race\",\n",
    "    \"gender\",\n",
    "    \"capital_gain\",\n",
    "    \"capital_loss\",\n",
    "    \"native_country\",\n",
    "]\n",
    "continuous_cols = [\"age\", \"hours_per_week\"]\n",
    "target_col = \"income_label\"\n",
    "\n",
    "tab_preprocessor = TabPreprocessor(\n",
    "    cat_embed_cols=cat_embed_cols,\n",
    "    continuous_cols=continuous_cols,\n",
    "    with_attention=True,\n",
    "    with_cls_token=True,  # this is optional\n",
    ")\n",
    "X_tab = tab_preprocessor.fit_transform(df_tr)\n",
    "target = df_tr[target_col].values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "2f28be46",
   "metadata": {},
   "outputs": [],
   "source": [
    "ft_transformer = FTTransformer(\n",
    "    column_idx=tab_preprocessor.column_idx,\n",
    "    cat_embed_input=tab_preprocessor.cat_embed_input,\n",
    "    continuous_cols=tab_preprocessor.continuous_cols,\n",
    "    embed_continuous_method=\"standard\",\n",
    "    input_dim=32,\n",
    "    kv_compression_factor=0.5,\n",
    "    n_blocks=3,\n",
    "    n_heads=4,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9f257152",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "epoch 1: 100%|██████████| 153/153 [00:22<00:00,  6.91it/s, loss=656]   \n",
      "epoch 2: 100%|██████████| 153/153 [00:07<00:00, 20.84it/s, loss=141]\n",
      "epoch 3: 100%|██████████| 153/153 [00:07<00:00, 20.75it/s, loss=137]\n",
      "epoch 4: 100%|██████████| 153/153 [00:07<00:00, 21.14it/s, loss=135]\n",
      "epoch 5: 100%|██████████| 153/153 [00:07<00:00, 21.05it/s, loss=134]\n"
     ]
    }
   ],
   "source": [
    "# for a full list of the params for the the ContrastiveDenoisingTrainer (which are many) please see the docs.\n",
    "# Note that using these params involves some knowledge of the routine and the architecture of the model used\n",
    "contrastive_denoising_trainer = ContrastiveDenoisingTrainer(\n",
    "    model=ft_transformer,\n",
    "    preprocessor=tab_preprocessor,\n",
    ")\n",
    "contrastive_denoising_trainer.pretrain(X_tab, n_epochs=5, batch_size=256)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0184783b",
   "metadata": {},
   "outputs": [],
   "source": [
    "contrastive_denoising_trainer.save(\n",
    "    path=\"pretrained_weights\", model_filename=\"contrastive_denoising_model.pt\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "119ca9df",
   "metadata": {},
   "source": [
    "some time has passed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "b60be9fd",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/pd/_2wz_qt16yq1fk6jn_xtxqk40000gn/T/ipykernel_71058/884975850.py:2: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
      "  contrastive_denoising_model = torch.load(\n"
     ]
    }
   ],
   "source": [
    "# some time has passed, we load the model with torch as usual:\n",
    "contrastive_denoising_model = torch.load(\n",
    "    \"pretrained_weights/contrastive_denoising_model.pt\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6576404c",
   "metadata": {},
   "source": [
    "NOW, AND THIS IS IMPORTANT! We have loaded the entire contrastive, denoising model. To proceed to the supervised training we ONLY need the attention-based model, which is the 'model' attribute of the trainer, let's have a look"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "3eab66ae",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "FTTransformer(\n",
       "  (cat_embed): SameSizeCatEmbeddings(\n",
       "    (embed): Embedding(322, 32, padding_idx=0)\n",
       "    (dropout): Dropout(p=0.0, inplace=False)\n",
       "  )\n",
       "  (cont_norm): Identity()\n",
       "  (cont_embed): ContEmbeddings(\n",
       "    INFO: [ContLinear = weight(n_cont_cols, embed_dim) + bias(n_cont_cols, embed_dim)]\n",
       "    (linear): ContLinear(n_cont_cols=2, embed_dim=32, embed_dropout=0.0)\n",
       "    (dropout): Dropout(p=0.0, inplace=False)\n",
       "  )\n",
       "  (encoder): Sequential(\n",
       "    (fttransformer_block0): FTTransformerEncoder(\n",
       "      (attn): LinearAttentionLinformer(\n",
       "        (dropout): Dropout(p=0.2, inplace=False)\n",
       "        (qkv_proj): Linear(in_features=32, out_features=96, bias=False)\n",
       "        (out_proj): Linear(in_features=32, out_features=32, bias=False)\n",
       "      )\n",
       "      (ff): FeedForward(\n",
       "        (w_1): Linear(in_features=32, out_features=84, bias=True)\n",
       "        (w_2): Linear(in_features=42, out_features=32, bias=True)\n",
       "        (dropout): Dropout(p=0.1, inplace=False)\n",
       "        (activation): REGLU()\n",
       "      )\n",
       "      (attn_normadd): NormAdd(\n",
       "        (dropout): Dropout(p=0.2, inplace=False)\n",
       "        (ln): LayerNorm((32,), eps=1e-05, elementwise_affine=True)\n",
       "      )\n",
       "      (ff_normadd): NormAdd(\n",
       "        (dropout): Dropout(p=0.1, inplace=False)\n",
       "        (ln): LayerNorm((32,), eps=1e-05, elementwise_affine=True)\n",
       "      )\n",
       "    )\n",
       "    (fttransformer_block1): FTTransformerEncoder(\n",
       "      (attn): LinearAttentionLinformer(\n",
       "        (dropout): Dropout(p=0.2, inplace=False)\n",
       "        (qkv_proj): Linear(in_features=32, out_features=96, bias=False)\n",
       "        (out_proj): Linear(in_features=32, out_features=32, bias=False)\n",
       "      )\n",
       "      (ff): FeedForward(\n",
       "        (w_1): Linear(in_features=32, out_features=84, bias=True)\n",
       "        (w_2): Linear(in_features=42, out_features=32, bias=True)\n",
       "        (dropout): Dropout(p=0.1, inplace=False)\n",
       "        (activation): REGLU()\n",
       "      )\n",
       "      (attn_normadd): NormAdd(\n",
       "        (dropout): Dropout(p=0.2, inplace=False)\n",
       "        (ln): LayerNorm((32,), eps=1e-05, elementwise_affine=True)\n",
       "      )\n",
       "      (ff_normadd): NormAdd(\n",
       "        (dropout): Dropout(p=0.1, inplace=False)\n",
       "        (ln): LayerNorm((32,), eps=1e-05, elementwise_affine=True)\n",
       "      )\n",
       "    )\n",
       "    (fttransformer_block2): FTTransformerEncoder(\n",
       "      (attn): LinearAttentionLinformer(\n",
       "        (dropout): Dropout(p=0.2, inplace=False)\n",
       "        (qkv_proj): Linear(in_features=32, out_features=96, bias=False)\n",
       "        (out_proj): Linear(in_features=32, out_features=32, bias=False)\n",
       "      )\n",
       "      (ff): FeedForward(\n",
       "        (w_1): Linear(in_features=32, out_features=84, bias=True)\n",
       "        (w_2): Linear(in_features=42, out_features=32, bias=True)\n",
       "        (dropout): Dropout(p=0.1, inplace=False)\n",
       "        (activation): REGLU()\n",
       "      )\n",
       "      (attn_normadd): NormAdd(\n",
       "        (dropout): Dropout(p=0.2, inplace=False)\n",
       "        (ln): LayerNorm((32,), eps=1e-05, elementwise_affine=True)\n",
       "      )\n",
       "      (ff_normadd): NormAdd(\n",
       "        (dropout): Dropout(p=0.1, inplace=False)\n",
       "        (ln): LayerNorm((32,), eps=1e-05, elementwise_affine=True)\n",
       "      )\n",
       "    )\n",
       "  )\n",
       ")"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "contrastive_denoising_model.model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "5158a581",
   "metadata": {},
   "outputs": [],
   "source": [
    "pretrained_model = contrastive_denoising_model.model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "8d9a5248",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "epoch 1: 100%|██████████| 153/153 [00:03<00:00, 50.99it/s, loss=0.383, metrics={'acc': 0.8218}]\n",
      "epoch 2: 100%|██████████| 153/153 [00:02<00:00, 53.22it/s, loss=0.328, metrics={'acc': 0.8505}]\n",
      "epoch 3: 100%|██████████| 153/153 [00:02<00:00, 54.50it/s, loss=0.309, metrics={'acc': 0.8588}]\n",
      "epoch 4: 100%|██████████| 153/153 [00:02<00:00, 53.90it/s, loss=0.299, metrics={'acc': 0.8641}]\n",
      "epoch 5: 100%|██████████| 153/153 [00:02<00:00, 54.02it/s, loss=0.292, metrics={'acc': 0.8665}]\n",
      "predict: 100%|██████████| 39/39 [00:00<00:00, 88.79it/s] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.8679496366055891\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "# and as always, ANY supervised model in this library has to go throuth the WideDeep class:\n",
    "model = WideDeep(deeptabular=pretrained_model)\n",
    "trainer = Trainer(model=model, objective=\"binary\", metrics=[Accuracy])\n",
    "\n",
    "trainer.fit(X_tab=X_tab, target=target, n_epochs=5, batch_size=256)\n",
    "\n",
    "# And, you know...we get a test metric\n",
    "X_tab_te = tab_preprocessor.transform(df_te)\n",
    "target_te = df_te[target_col].values\n",
    "\n",
    "preds = trainer.predict(X_tab=X_tab_te)\n",
    "test_acc = accuracy_score(target_te, preds)\n",
    "print(test_acc)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
